<template>
  <div class="page-box">
    <el-button type="primary" plain icon="el-icon-plus" class="add-btn" size="small" @click="showDialog=true">新增</el-button>
    <el-tabs v-model="activeName" :before-leave="beforeLeave" @tab-click="handleClick">
      <el-tab-pane label="文字链接" name="1">
        <!-- 表格区域 -->
        <div class="table-box">
          <el-table
            :data="list"
            style="width: 100%"
            border
          >
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="des" label="链接描述" />
            <el-table-column prop="type" label="链接类型">
              <template #default="{row}">
                <el-tag v-if="row.type==='1'">文字类型</el-tag>
                <el-tag v-else-if="row.type==='2'" type="success">图片类型</el-tag>
                <el-tag v-else type="warning">未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="url" label="链接地址" />
            <el-table-column label="操作" align="center">
              <template #default="{row}">
                <el-button type="primary" circle icon="el-icon-edit" @click="doEdit(row.id)" />
                <el-button type="danger" circle icon="el-icon-delete" @click="doDel(row.id)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="图片链接" name="2">
        <!-- 表格区域 -->
        <div class="table-box">
          <el-table
            :data="list"
            style="width: 100%"
            border
          >
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="des" label="链接描述" />
            <el-table-column prop="img" label="链接图片">
              <template #default="{row}">
                <el-image
                  style="height: 100px"
                  :src="row.img?'http://124.223.14.236:8060/'+row.img:''"
                >
                  <div slot="error" class="image-slot-error">
                    <i class="el-icon-picture-outline" />
                  </div>
                  <div slot="placeholder" class="image-slot-loading">
                    加载中<span class="dot">...</span>
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="链接类型">
              <template #default="{row}">
                <el-tag v-if="row.type==='1'">文字类型</el-tag>
                <el-tag v-else-if="row.type==='2'" type="success">图片类型</el-tag>
                <el-tag v-else type="warning">未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="url" label="链接地址" />
            <el-table-column label="操作" align="center">
              <template #default="{row}">
                <el-button type="primary" circle icon="el-icon-edit" @click="doEdit(row.id)" />
                <el-button type="danger" circle icon="el-icon-delete" @click="doDel(row.id)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 分页区域 -->
    <div class="pagination-box">
      <el-row type="flex" justify="end">
        <el-pagination
          background
          :current-page="queryParams.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryParams.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- 新增和编辑弹出对话框 -->
    <el-dialog title="dialogTitle" :visible.sync="showDialog" width="45%" @close="closeDialog">
      <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="链接类型" prop="type">
          <!-- 分类下拉框 v-model的值为当前被选中的el-option的 value 属性值 -->
          <!-- v-model绑定的值和value绑定的值必须是同种类型的，因为advimgpos是字符串所以此处将id转成字符串 -->
          <el-select v-model="formData.type" clearable placeholder="请选择">
            <el-option label="文章类型" value="1" />
            <el-option label="图片类型" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.type==='1'" label="链接标题" prop="title">
          <el-input v-model="formData.title" style="width:90%" placeholder="请输入链接标题" />
        </el-form-item>
        <el-form-item label="链接地址" prop="url">
          <el-input v-model="formData.url" style="width:90%" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="链接描述" prop="des">
          <el-input v-model="formData.des" style="width:90%" type="textarea" placeholder="请输入链接描述" :autosize="{ minRows: 2, maxRows: 4}" />
        </el-form-item>
        <el-form-item v-if="formData.type==='2'" label="广告图" prop="img">
          <!-- 此处以formData中advimgsrc是否为空控制上传按钮的渲染，缺点是必须等待上传完成后按钮才会隐藏 -->
          <!-- 使用fileList是否为空也是一样，但是图片上传完成后会上下抖动一次，已找到解决抖动方法，改用fileList -->
          <!-- 使用布尔值变量判断可以在点击上传，图片上传成功前就能隐藏按钮，但麻烦，此处不用 -->
          <el-upload
            action="http://124.223.14.236:8060/admin/common/upload?type=images"
            :headers="{ 'X-Token': this.$store.getters.token}"
            list-type="picture"
            :on-success="handleSuccess"
            :limit="1"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addLink, delLink, editLink, getLinkDetail, getLinkList } from '@/api/adv/link'
export default {
  data() {
    return {
      queryParams: {
        type: 1,
        page: 1,
        limit: 10
      },
      activeName: '1',
      list: [],
      total: 0,
      showDialog: false,
      formData: {
        type: '',
        title: '',
        des: '',
        url: '',
        img: ''
      },
      fileList: [],
      rules: {
        type: [{ required: true, message: '请选择链接类型', trigger: 'blur' }],
        title: [{ required: true, message: '请输入链接标题', trigger: 'blur' }],
        des: [{ required: true, message: '请输入链接描述', trigger: 'blur' }],
        url: [{ required: true, message: '请输入链接地址', trigger: 'blur' }],
        img: [{ required: true, message: '请上传链接图片', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 表格数据初始化
    async initData() {
      const res = await getLinkList(this.queryParams)
      this.list = res.data
      this.total = res.count
    },
    // 每次点击tab时触发(点击当前tab也会触发)
    handleClick(tab, event) {
      this.queryParams.type = tab.name
      this.initData()
    },
    // tab切换时触发(点击当前tab不会触发)
    beforeLeave(activeName, oldActiveName) {
      console.log(activeName, oldActiveName)
    },
    // 切换每页显示数量
    handleSizeChange(value) {
      this.queryParams.limit = value
      this.queryParams.page = 1
      this.initData()
    },
    // 切换分页
    handleCurrentChange(value) {
      this.queryParams.page = value
      this.initData()
    },
    async submit() {
      this.$refs.form.validate(async(isOK) => {
        if (!isOK) return
        if (this.formData.id) {
          await editLink(this.formData)
          this.$message.success('编辑友情链接成功！')
        } else {
          await addLink(this.formData)
          this.$message.success('新增友情链接成功！')
        }
      })
      // 关闭dialog自动重置表单数据，重新渲染表格数据
      this.showDialog = false
      this.initData()
    },
    async doEdit(id) {
      this.formData = await getLinkDetail(id)
      if (this.formData.img) {
        this.fileList.push({ url: 'http://124.223.14.236:8060/' + this.formData.img })
      }
      this.showDialog = true
    },
    async doDel(id) {
      this.$confirm('确认删除该友情链接?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delLink(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 处理删除最后一页最后一条数据
        if (this.list.length === 1 && this.queryParams.page > 1) {
          this.queryParams.page--
        }
        // 刷新表格
        this.initData()
      }).catch(() => {
        return false
      })
    },
    closeDialog() {
      this.formData = {
        type: '',
        title: '',
        des: '',
        url: '',
        img: ''
      }
      this.fileList = []
      this.$refs.form.clearValidate()
    },
    // 图片上传成功
    handleSuccess(reponse, file, fileList) {
      this.formData.img = reponse.data.savePath
    }
  }
}
</script>

<style lang="scss" scoped>
.page-box{
  position: relative;
  .add-btn{
    position: absolute;
    right: 20px;
    top: 20px;
    z-index: 1000;
  }
}

</style>
